//
//  WBOAuthViewController.swift
//  XLWB
//
//  Created by MacBook on 16/7/3.
//  Copyright © 2016年 MacBook. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        view.backgroundColor = UIColor.white()
        
        //取消滚动视图-返回的授权页面默认是全屏的
        webView.scrollView.isScrollEnabled = false
        
        webView.delegate = self
        //设置导航栏
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFil))
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        //加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURi)"
        
        guard let url = URL(string: urlString) else {
        
            return
        }
        
        //建立请求
        let request = URLRequest(url: url)
        
        //加载请求
        webView.loadRequest(request)
    }

    
    //MARK--自动填充
    @objc private func autoFil() {
    
        //准备js
        let js = "document.getElementById('userId').value = '17180102421';" + "document.getElementById('passwd').value = '122468nana';"
        
        //执行js
        webView.stringByEvaluatingJavaScript(from: js)
    
    }
    
    @objc private func close() {
    
        SVProgressHUD.dismiss()
    
        dismiss(animated: true, completion: nil)
    }
}

extension WBOAuthViewController: UIWebViewDelegate {

    //webView将要加载请求

    //webView: webView
    //request:要加载的请求
    //navigationType:导航类型
    //returns:是否加载request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //1.如果请求地址包含http://baidu.com 不加载页面 / 加载页面
        if request.url?.absoluteString?.hasPrefix(WBRedirectURi) == false {
            return true
        }

        
        //2.从http://baidu.com 回调地址的"查询字符串中"查找'code='\
        //如果有,授权成功,否则失败
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消授权")
            close()
            
            return false
        }
        
        //3.从query字符串取出授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码-\(code)")
        
        //使用授权码获取[换取]AccessToken
        WBNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
                
               SVProgressHUD.showInfo(withStatus: "网络请求失败")

            } else {
               SVProgressHUD.showInfo(withStatus: "登录成功")
                //转跳界面,通过通知发送登录成功消息
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotification), object: nil)
                
                //关闭窗口
                self.close()
            
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }

}
